package com.ruoyi.project.system.controller

import com.ruoyi.common.constant.UserConstants
import com.ruoyi.common.utils.StringUtils
import com.ruoyi.common.utils.poi.ExcelUtil
import com.ruoyi.framework.aspectj.lang.annotation.Log
import com.ruoyi.framework.aspectj.lang.enums.BusinessType
import com.ruoyi.framework.security.service.SysPermissionService
import com.ruoyi.framework.security.service.TokenService
import com.ruoyi.framework.web.controller.BaseController
import com.ruoyi.framework.web.domain.AjaxResult
import com.ruoyi.framework.web.page.TableDataInfo
import com.ruoyi.project.system.domain.SysDept
import com.ruoyi.project.system.domain.SysRole
import com.ruoyi.project.system.domain.SysUser
import com.ruoyi.project.system.domain.SysUserRole
import com.ruoyi.project.system.service.ISysDeptService
import com.ruoyi.project.system.service.ISysRoleService
import com.ruoyi.project.system.service.ISysUserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import javax.servlet.http.HttpServletResponse

/**
 * 角色信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/role")
open class SysRoleController : BaseController() {
    @Autowired
    private val roleService: ISysRoleService? = null

    @Autowired
    private val tokenService: TokenService? = null

    @Autowired
    private val permissionService: SysPermissionService? = null

    @Autowired
    private val userService: ISysUserService? = null

    @Autowired
    private val deptService: ISysDeptService? = null
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
    fun list(role: SysRole?): TableDataInfo {
        startPage()
        val list = roleService!!.selectRoleList(role)
        return getDataTable(list)
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:role:export')")
    @PostMapping("/export")
    fun export(response: HttpServletResponse, role: SysRole?) {
        val list = roleService!!.selectRoleList(role)
        val util = ExcelUtil(SysRole::class.java)
        util.exportExcel(response, list, "角色数据")
    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = ["/{roleId}"])
    fun getInfo(@PathVariable roleId: Long?): AjaxResult {
        roleService!!.checkRoleDataScope(roleId)
        return AjaxResult.success(roleService.selectRoleById(roleId))
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    fun add(@Validated @RequestBody role: SysRole): AjaxResult {
        if (UserConstants.NOT_UNIQUE == roleService!!.checkRoleNameUnique(role)) {
            return AjaxResult.Companion.error("新增角色'" + role.roleName + "'失败，角色名称已存在")
        } else if (UserConstants.NOT_UNIQUE == roleService.checkRoleKeyUnique(role)) {
            return AjaxResult.Companion.error("新增角色'" + role.roleName + "'失败，角色权限已存在")
        }
        role.createBy = username
        return toAjax(roleService.insertRole(role))
    }

    /**
     * 修改保存角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    fun edit(@Validated @RequestBody role: SysRole): AjaxResult {
        roleService!!.checkRoleAllowed(role)
        roleService.checkRoleDataScope(role.roleId)
        if (UserConstants.NOT_UNIQUE == roleService.checkRoleNameUnique(role)) {
            return AjaxResult.error("修改角色'" + role.roleName + "'失败，角色名称已存在")
        } else if (UserConstants.NOT_UNIQUE == roleService.checkRoleKeyUnique(role)) {
            return AjaxResult.error("修改角色'" + role.roleName + "'失败，角色权限已存在")
        }
        role.updateBy = username
        if (roleService.updateRole(role) > 0) {
            // 更新缓存用户权限
            val loginUser = loginUser
            if (StringUtils.isNotNull(loginUser.user) && !loginUser.user!!.isAdmin) {
                loginUser.permissions = permissionService!!.getMenuPermission(loginUser.user!!)
                loginUser.user = userService!!.selectUserByUserName(loginUser.user!!.userName)
                tokenService!!.setLoginUser(loginUser)
            }
            return AjaxResult.Companion.success()
        }
        return AjaxResult.Companion.error("修改角色'" + role.roleName + "'失败，请联系管理员")
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    fun dataScope(@RequestBody role: SysRole): AjaxResult {
        roleService!!.checkRoleAllowed(role)
        roleService.checkRoleDataScope(role.roleId)
        return toAjax(roleService.authDataScope(role))
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    fun changeStatus(@RequestBody role: SysRole): AjaxResult {
        roleService!!.checkRoleAllowed(role)
        roleService.checkRoleDataScope(role.roleId)
        role.updateBy = username
        return toAjax(roleService.updateRoleStatus(role))
    }

    /**
     * 删除角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    fun remove(@PathVariable roleIds: Array<Long?>): AjaxResult {
        return toAjax(roleService!!.deleteRoleByIds(roleIds))
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    fun optionselect(): AjaxResult {
        return AjaxResult.success(roleService!!.selectRoleAll())
    }

    /**
     * 查询已分配用户角色列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/authUser/allocatedList")
    fun allocatedList(user: SysUser?): TableDataInfo {
        startPage()
        val list = userService!!.selectAllocatedList(user)
        return getDataTable(list)
    }

    /**
     * 查询未分配用户角色列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/authUser/unallocatedList")
    fun unallocatedList(user: SysUser?): TableDataInfo {
        startPage()
        val list = userService!!.selectUnallocatedList(user)
        return getDataTable(list)
    }

    /**
     * 取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    fun cancelAuthUser(@RequestBody userRole: SysUserRole?): AjaxResult {
        return toAjax(roleService!!.deleteAuthUser(userRole))
    }

    /**
     * 批量取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    fun cancelAuthUserAll(roleId: Long?, userIds: Array<Long?>?): AjaxResult {
        return toAjax(roleService!!.deleteAuthUsers(roleId, userIds))
    }

    /**
     * 批量选择用户授权
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    fun selectAuthUserAll(roleId: Long?, userIds: Array<Long?>): AjaxResult {
        roleService!!.checkRoleDataScope(roleId)
        return toAjax(roleService.insertAuthUsers(roleId, userIds))
    }

    /**
     * 获取对应角色部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = ["/deptTree/{roleId}"])
    fun deptTree(@PathVariable("roleId") roleId: Long?): AjaxResult {
        val ajax: AjaxResult = AjaxResult.success()
        ajax["checkedKeys"] = deptService!!.selectDeptListByRoleId(roleId)
        ajax["depts"] = deptService.selectDeptTreeList(SysDept())
        return ajax
    }
}
